﻿/*
    Copyright Multi-Soft co.2009 
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.IO;
using System.Data;

using Rmlife.Common;
using Rmlife.Config;
using Rmlife.Data;
using Rmlife.Model;
using Rmlife.Site;
using Rmlife.Control;

namespace Rmlife.Web
{
    /// <summary>
    /// 站点工具类
    /// </summary>
    public class WebUtils
    {
        /// <summary>
        /// 系统管理员名称
        /// </summary>
        public static string __Administrator = "admin";
        /// <summary>
        /// 系统管理员ID
        /// </summary>
        public static int __AdministratorID = BaseConfigs.GetFounderUid;

        /// <summary>
        /// 获得产品版本类型名称
        /// </summary>
        /// <returns></returns>
        public static string GetProductTypeName
        {
            get
            {
                return "";
            }
        }

        #region "导出方法"
        /// <summary>
        /// 导出控件数据到EXCEL
        /// </summary>
        /// <param name="eControl"></param>
        public static void ExportDataToExcel(System.Web.UI.WebControls.WebControl eControl)
        {
            ExportDataToExcel(eControl, string.Empty, null);
        }
        public static void ExportDataToExcel(System.Web.UI.WebControls.WebControl eControl, string[] removeColumns)
        {
            ExportDataToExcel(eControl, string.Empty, removeColumns);
        }
        public static void ExportDataToExcel(System.Web.UI.WebControls.WebControl eControl, string filenamePrefix)
        {
            ExportDataToExcel(eControl, filenamePrefix, null);
        }
        /// <summary>
        /// 导出控件数据到EXCEL
        /// </summary>
        /// <param name="eControl"></param>
        public static void ExportDataToExcel(System.Web.UI.WebControls.WebControl eControl, string filenamePrefix, string[] removeColumns)
        {
            #region 预处理数据

            if (eControl is Rmlife.Control.DataGrid)
            {
                Rmlife.Control.DataGrid obj = (Rmlife.Control.DataGrid)eControl;
                if (obj == null) return;

                for (int i = 0; i < obj.Columns.Count; i++)
                {
                    //obj.Columns[i].SortExpression = string.Empty;
                    if (obj.Columns[i].HeaderText == string.Empty)
                    {
                        obj.Columns[i].Visible = false;
                    }

                    if (removeColumns != null)
                    {
                        if (Utils.InArray(i.ToString(), removeColumns))
                        {
                            obj.Columns[i].Visible = false;
                        }
                    }
                }
                eControl = obj;
            }

            #endregion

            string sFileName = filenamePrefix + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";

            string filecontenttype = "application/vnd.ms-excel";
            System.Web.HttpContext.Current.Response.Clear();
            System.Web.HttpContext.Current.Response.Charset = "UTF-8";
            System.Web.HttpContext.Current.Response.Buffer = true;

            System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
            System.Web.HttpContext.Current.Response.ContentType = filecontenttype;

            eControl.EnableViewState = false;
            eControl.Attributes.Add("style", "vnd.ms-excel.numberformat:@");

            System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("ZH-CN", false);
            System.IO.StringWriter sw = new System.IO.StringWriter(ci);
            System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
            eControl.RenderControl(htw);

            // TO DO:全屏时不支持下面这句，一用就会关闭窗口，暂时封闭。090427-v1.52-田小岐
            if (!GeneralConfigs.GetConfig().FullScreen)
            {
                System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + sFileName);
            }

            string sText = sw.ToString();


            // 去掉超链接
            sText = System.Text.RegularExpressions.Regex.Replace(sText, "<a .+?>(.+?)</a>", "$1", System.Text.RegularExpressions.RegexOptions.Multiline | System.Text.RegularExpressions.RegexOptions.IgnoreCase | RegexOptions.Singleline);


            FileStream fs = File.Create(System.Web.HttpContext.Current.Server.MapPath(WebConfigs.Paths.CacheRoot + sFileName));
            StreamWriter ws = new StreamWriter(fs, Encoding.UTF8);
            ws.Write(sText);
            ws.Close();

            System.Web.HttpContext.Current.Response.WriteFile(System.Web.HttpContext.Current.Server.MapPath(WebConfigs.Paths.CacheRoot + sFileName));
            System.Web.HttpContext.Current.Response.Flush();
            System.Web.HttpContext.Current.Response.Close();

            if (File.Exists(System.Web.HttpContext.Current.Server.MapPath(WebConfigs.Paths.CacheRoot + sFileName)))
            {
                File.SetAttributes(System.Web.HttpContext.Current.Server.MapPath(WebConfigs.Paths.CacheRoot + sFileName), FileAttributes.Normal);
                File.Delete(System.Web.HttpContext.Current.Server.MapPath(WebConfigs.Paths.CacheRoot + sFileName));
            }

            System.Web.HttpContext.Current.Response.End();

        }
        #endregion       

        #region GetPageSplitWhere
        /// <summary>
        /// 分页条件判断TextBox
        /// </summary>
        public static string GetPageSplitWhere(Rmlife.Control.TextBox txtwc, string webReq, string keyWhere, ref string _keyword)
        {
            string strWhere = "";

            if (!string.IsNullOrEmpty(txtwc.Text.Trim()))
            {
                if (webReq != "")
                {
                    _keyword = webReq;

                    if (txtwc.Text != webReq)
                    {
                        _keyword = txtwc.Text;
                    }

                    strWhere += " and " + keyWhere + " like '%" + _keyword + "%'";
                }
                else
                {
                    strWhere += " and " + keyWhere + " like '%" + txtwc.Text + "%'";

                }
            }

            return strWhere;
        }


        /// <summary>
        /// 分页条件判断DropDownList
        /// </summary>
        public static string GetPageSplitWhere(Rmlife.Control.DropDownList drpList, string webReq, string keyWhere, ref string _keyword)
        {
            string strWhere = "";

            if (drpList.SelectedValue != "")
            {
                if (webReq != "")
                {
                    _keyword = webReq;

                    if (drpList.SelectedValue != webReq)
                    {
                        _keyword = drpList.SelectedValue;
                    }

                    strWhere += " and " + keyWhere + " = '" + _keyword + "'";
                }
                else
                {
                    strWhere += " and " + keyWhere + " = '" + drpList.SelectedValue + "'";

                }
            }

            return strWhere;
        }

        /// <summary>
        /// 分页条件判断Calendar
        /// </summary>
        public static string GetPageSplitWhere(Rmlife.Control.Calendar cldStart, Rmlife.Control.Calendar cldEnd, string webReqStart, string webReqEnd, string keyWhere, ref string _keywordStart, ref string _keywordEnd)
        {
            string strWhere = "";

            if (cldStart.SelectedDate < cldEnd.SelectedDate)
            {
                if (cldStart.SelectedDate != System.Convert.ToDateTime(GetDateDefault()) || cldEnd.SelectedDate != System.Convert.ToDateTime(GetDateDefault()))
                {
                    if (webReqStart != "" || webReqEnd != "")
                    {
                        if (webReqStart != "")
                        {
                            _keywordStart = webReqStart;

                            if (cldStart.SelectedDate.ToShortDateString() != webReqStart)
                            {
                                _keywordStart = cldStart.SelectedDate.ToShortDateString();
                            }

                            strWhere += " and " + keyWhere + ">='" + _keywordStart + "'";
                        }

                        if (webReqEnd != "")
                        {
                            _keywordEnd = webReqEnd;

                            if (cldEnd.SelectedDate.ToShortDateString() != webReqEnd)
                            {
                                _keywordEnd = cldEnd.SelectedDate.ToShortDateString();
                            }

                            strWhere += " and " + keyWhere + "<='" + _keywordEnd + "'";
                        }

                    }
                    else
                    {
                        if (cldStart.SelectedDate != System.Convert.ToDateTime(GetDateDefault())) strWhere += " and " + keyWhere + ">='" + cldStart.SelectedDate.ToShortDateString() + "'";
                        if (cldEnd.SelectedDate != System.Convert.ToDateTime(GetDateDefault())) strWhere += " and " + keyWhere + "<='" + cldEnd.SelectedDate.ToShortDateString() + "'";
                    }
                }
            }
            else
            {
                strWhere += "error";
            }

            return strWhere;
        }
        #endregion

        #region 日历控件默认值
        public static string GetDateDefault()
        {
            string retDate = "1899-12-30";
            return retDate;
        }

        public static string GetIsDateNull(string strDate)
        {
            string retDate = "";
            if (strDate != GetDateDefault())
                retDate = strDate;
            return retDate;
        }

        #endregion

        #region "调试方法"
        /// <summary>
        /// 写本地日志
        /// </summary>
        /// <param name="logContent"></param> 
        public static void WriteLog(string logContent)
        {
            string LogFileName = Utils.GetMapPath(string.Format("{0}event.log", WebConfigs.Paths.DataRoot));
            StringBuilder builder = new StringBuilder();
            builder.Append(DateTime.Now);
            builder.Append("\t");
            builder.Append(Environment.MachineName);
            builder.Append("\t");
            builder.Append(logContent);
            builder.Append("\r\n");

            if (File.Exists(LogFileName))
                File.SetAttributes(LogFileName, FileAttributes.Normal);

            using (FileStream fs = new FileStream(LogFileName, FileMode.Append, FileAccess.Write, FileShare.Write))
            {
                Byte[] info = System.Text.Encoding.UTF8.GetBytes(builder.ToString());
                fs.Write(info, 0, info.Length);
                fs.Close();
            }
        }
        #endregion
    }
}
